package com.frank.libandroid;

import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.RecyclerView;

import com.frank.libandroid.butterknife.ButterKnife;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public abstract class BaseAdapter<V extends ViewDataBinding, M> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    protected List<M> mList = new ArrayList<>();

    public void setData(Collection<M> list) {
        mList.clear();
        if (list != null) {
            mList.addAll(list);
        }
        notifyDataSetChanged();
    }

    public List<M> getData() {
        return mList;
    }

    public void addData(List<M> list) {
        if (list != null) {
            mList.addAll(list);
        }
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        Class<Object> generic = (Class<Object>) ReflectUtil.getGeneric(this, 0);
        try {
            Method method = generic.getMethod("inflate", LayoutInflater.class, ViewGroup.class, boolean.class);
            V binding = (V) method.invoke(null, LayoutInflater.from(parent.getContext()), parent, false);
            binding.getRoot().setTag(R.id.tag_binding, binding);
            ButterKnife.bindAdapter(this, binding);
            return new RecyclerView.ViewHolder(binding.getRoot()) {
            };
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        V binding = (V) holder.itemView.getTag(R.id.tag_binding);
        binding.getRoot().setTag(R.id.tag_bean, mList.get(position));
        binding.getRoot().setTag(R.id.tag_position, position);
        onBindData(binding, mList.get(position), position);
    }

    protected void onBindData(V binding, M bean, int position) {
        ((ViewDataBinding) binding).setVariable(1, bean);
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }
}
